import { useEffect, useState } from 'react'
import NotificationService from '../services/notificationService'

export function useNotifications() {
  const [permission, setPermission] = useState<NotificationPermission>('default')
  const [isEnabled, setIsEnabled] = useState(false)

  useEffect(() => {
    // 初始化通知服务
    const initNotifications = async () => {
      const notificationService = NotificationService.getInstance()
      const currentPermission = notificationService.getPermissionStatus()
      setPermission(currentPermission)
      
      // 检查设置中是否启用了通知
      const settings = notificationService.getSettings()
      setIsEnabled(settings.enabled && currentPermission === 'granted')
      
      // 如果权限已授予且设置启用，启动提醒服务
      if (currentPermission === 'granted' && settings.enabled) {
        console.log('通知服务已启动')
      }
    }

    initNotifications()

    // 监听页面可见性变化
    const handleVisibilityChange = () => {
      if (!document.hidden) {
        const notificationService = NotificationService.getInstance()
        // 页面重新可见时，检查权限状态
        const newPermission = notificationService.getPermissionStatus()
        if (newPermission !== permission) {
          setPermission(newPermission)
          setIsEnabled(newPermission === 'granted' && notificationService.getSettings().enabled)
        }
      }
    }

    document.addEventListener('visibilitychange', handleVisibilityChange)

    return () => {
      document.removeEventListener('visibilitychange', handleVisibilityChange)
    }
  }, [permission])

  const requestPermission = async () => {
    const notificationService = NotificationService.getInstance()
    const newPermission = await notificationService.requestPermission()
    setPermission(newPermission)
    setIsEnabled(newPermission === 'granted')
    return newPermission
  }

  const sendTestNotification = async () => {
    if (!isEnabled) {
      console.warn('通知未启用')
      return false
    }

    const notificationService = NotificationService.getInstance()
    const result = await notificationService.testNotification()

    return result !== null
  }

  return {
    permission,
    isEnabled,
    requestPermission,
    sendTestNotification,
    notificationService: NotificationService.getInstance()
  }
}
